﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="ReportManagement.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using GenericTools;
using System.Text.RegularExpressions;
using DataModels.Common;
using DataModels.Enumerations;
using GenericTools.Models;
using ReportingManagement.Components;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        #region Class Constants
        const string MONTH = "MONTH";
        const string YEAR = "YEAR";
        #endregion

        private bool tabPageReportManagementLoaded = false;

        #region Report Details
        private bool tabPageReportDetailsLoaded = false;
        private bool tabPageReportManagementReportMergeLoaded = false;

        private void tabPageReportDetails_Enter(object sender, EventArgs e)
        {
            try
            {
                if (!tabPageReportDetailsLoaded)
                {
                    LoadReportNameList();
                    rdoMergeNation.Checked = true;
                    tabPageReportDetailsLoaded = true;
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void LoadReportNameList()
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetAllExpectedReports();
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboReportName.Items.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row["ReportName"].ToString();
                item.Value = row["RepID"];
                cboReportName.Items.Add(item);
            }
            try
            {
                cboReportName.SelectedIndex = 0;
            }
            catch { }
        }

        private void LoadReportDataLocation()
        {
            ListItem item = (ListItem)cboReportName.SelectedItem;
            int reportID = Int32.Parse(item.Value.ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetReportDataLocations(reportID);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            int index = -1;
            dgvReportDetails.Rows.Clear();
            foreach (DataRow r in dataTable.Rows)
            {
                index = dgvReportDetails.Rows.Add();
                DataGridViewRow row = dgvReportDetails.Rows[index];
                row.Cells["MeasureNo"].Value = r["MeasureNo"];
                row.Cells["DataDescription"].Value = r["DataDescription"];
                row.Cells["DataPosition"].Value = r["DataPosition"];
                row.Cells["DataType"].Value = r["DataType"];
                row.Cells["ShortCode"].Value = r["ShortCode"];
            }
            try
            {
                // We may need this for existing forms
                //dgvReportDetails.Rows[0].ReadOnly = true;
                //dgvReportDetails.Rows[1].ReadOnly = true;
                //dgvReportDetails.Rows[2].ReadOnly = true;
            }
            catch { }
        }

        private void btnCreateNewReport_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            try
            {
                AddReport addReport = new AddReport(this.authenticatedUser);
                DialogResult response = addReport.ShowDialog(this);
                if (response == System.Windows.Forms.DialogResult.OK)
                {
                    Utilities.ClearCache(DataCache.REPORTS_DETAILS);
                    LoadReportNameList();
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void cboReportName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                ListItem item = (ListItem)cboReportName.SelectedItem;
                int reportID = Int32.Parse(item.Value.ToString());

                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                DataTable dataTable = Utilities.GetReportDetails(reportID);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";

                string repVersion = dataTable.Rows[0]["RepVersion"].ToString();
                txtReportKeyword.Text = repVersion;

                LoadReportDataLocation();

                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                bool canDelete = Utilities.ReportCanBeDeleted(reportID);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";

                btnDeleteReport.Enabled = canDelete;
            }
            catch (Exception ex)
            {
                if (tabPageReportDetailsLoaded) DisplayErrorMessage(ex);
            }
        }

        private void btnDeleteReport_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            DialogResult response = MessageBox.Show(this,
                String.Format("Are you sure you want to delete {0} and all its associated data?", cboReportName.Text),
                AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (response == System.Windows.Forms.DialogResult.Yes)
            {
                ListItem item = (ListItem) cboReportName.SelectedItem;
                int reportID = Int32.Parse(item.Value.ToString());

                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                Utilities.DeleteReport(reportID);
                Utilities.ClearCache(DataCache.REPORTS_DETAILS);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";

                LoadReportNameList();
            }
        }

        private void dgvReportDetails_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            int count = dgvReportDetails.Rows.Count;
            for (int i = 0; i < count; i++)
            {
                DataGridViewRow row = dgvReportDetails.Rows[i];
                row.Cells["DataPosition"].Value = i + 1;
            }
        }

        private void dgvReportDetails_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            dgvReportDetails_UserAddedRow(null, null);
        }

        private void btnResetReportDetails_Click(object sender, EventArgs e)
        {
            cboReportName_SelectedIndexChanged(null, null);
        }

        private void btnSaveReportChanges_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            try
            {
                btnSaveReportChanges.Enabled = false;

                int currentDataLocationCount = dgvReportDetails.Rows.Count - 1;
                if (currentDataLocationCount < Utilities.MINIMUM_DATA_COMPONENTS)
                {
                    MessageBox.Show(this,
                        String.Format("Report data location count is smaller that accepted value. " +
                            "Minimum accepted count is {0}", Utilities.MINIMUM_DATA_COMPONENTS),
                        AppConfiguration.ApplicationName,
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    btnSaveReportChanges.Enabled = true;
                    return;
                }               

                DialogResult response = MessageBox.Show(this,
                    "Are you sure you want to save changes of data location of this report?",
                    AppConfiguration.ApplicationName,
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (response == System.Windows.Forms.DialogResult.Yes)
                {
                    ListItem item = (ListItem)cboReportName.SelectedItem;
                    int reportID = Int32.Parse(item.Value.ToString());

                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    //DataTable dataTable = Utilities.GetReportDataLocations(reportID);
                    int previousDataLocationCount = Utilities.GetReportDataLocationsCount(reportID);
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    
                    //int previousDataLocationCount = dataTable.Rows.Count;
                    if (currentDataLocationCount < previousDataLocationCount)
                    {
                        response = MessageBox.Show(this,
                            "Report data locations you have set differ greatly with existing data locations. " +
                            "You will need to set up again the rules governing these data locations." + 
                            "\n\nDo you want to continue?",
                            AppConfiguration.ApplicationName,
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (response == System.Windows.Forms.DialogResult.No)
                        {
                            btnSaveReportChanges.Enabled = true;
                            return;
                        }
                    }

                    string[][] data = new string[currentDataLocationCount][];
                    for (int i = 0; i < currentDataLocationCount; i++)
                    {
                        DataGridViewRow r = dgvReportDetails.Rows[i];
                        int cellCount = r.Cells.Count; 
                        data[i] = new string[cellCount];
                        for (int j = 1; j < cellCount; j++) //invisible measureno should not be included
                        {
                            DataGridViewCell cell = r.Cells[j];
                            string value = null;
                            try 
                            { 
                                value = cell.Value.ToString(); 
                            }
                            catch { }
                            if (String.IsNullOrEmpty(value))
                            {
                                MessageBox.Show(this, "Please provide valid data at this row", 
                                    AppConfiguration.ApplicationName,
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                if (cell.Visible) cell.Selected = true;

                                btnSaveReportChanges.Enabled = true;
                                return;
                            }
                            else data[i][j-1] = value;
                        }
                    }
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    bool updated = Utilities.UpdateReportKeyword(reportID, txtReportKeyword.Text);
                    if (updated)
                    {
                        Utilities.SetReportDataLocations(reportID, data);
                        Utilities.ClearCache(DataCache.REPORTS_DETAILS);

                        MessageBox.Show(this,
                            "You have successfully saved report changes",
                            AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        Cursor.Current = Cursors.Default;
                        toolStripStatusLabel.Text = "Ready";

                        tabPageReportRulesLoaded = false;
                        cboReportName_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        MessageBox.Show(this,
                            "Report keyword must be unique. Selected keyword is already in use, please select another one!",
                            AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        btnSaveReportChanges.Enabled = true;
                        return;
                    }
                }
                btnSaveReportChanges.Enabled = true;
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
                btnSaveReportChanges.Enabled = true;
            }
        }
        #endregion

        #region Report Rules
        private bool tabPageReportRulesLoaded = false;
        private bool updating = true;

        #region Event Handlers
        private void cboReportsForRules_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                txtRuleDescription.Text = String.Empty;
                txtSpecificValueMeasure2.Text = String.Empty;
                txtSumDiffMeasure2.Text = String.Empty;
                txtExpresionMeasure2.Text = String.Empty;
                txtAverageMeasure2.Text = String.Empty;

                LoadReportRuleDetails();
                //if (updating) LoadReportRulesIntoListView();
                //else btnAddNewRule_Click(null, null);
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void tabPageReportRules_Enter(object sender, EventArgs e)
        {
            try
            {
                if (!tabPageReportRulesLoaded)
                {
                    LoadReportNameListForRules();

                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable comparionsDataTable = Utilities.GetAllComparison();
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cboRuleComparison.ValueMember = "ComparisonType";
                    cboRuleComparison.DisplayMember = "ComparisonSign";
                    cboRuleComparison.DataSource = comparionsDataTable;

                    tabPageReportRulesLoaded = true;
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void listViewReportRules_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //LoadReportRuleDetails();
                if (listViewReportRules.SelectedItems.Count == 0) return;
                ListViewItem item = listViewReportRules.SelectedItems[0];
                DataRow row = (DataRow)item.Tag;

                txtRuleDescription.Text = row["RuleDescription"].ToString();
                int measure1Position = Int32.Parse(row["MeasurePosNo"].ToString());
                int comparison = Int32.Parse(row["ComparisonType"].ToString());
                bool multicomparison = bool.Parse(row["Multicomparison"].ToString());
                string comparedTo = row["ComparedToOrderPos"].ToString();

                int measure1SelectedIndex = -1;
                bool measure1IndexFound = false;
                foreach (ListItem i in cboRuleMeasure1.Items)
                {
                    if (!measure1IndexFound) measure1SelectedIndex++;
                    int pos = Int32.Parse(i.Value.ToString());
                    if (pos == measure1Position) measure1IndexFound = true;
                    i.Value = pos;
                }
                cboRuleMeasure1.SelectedIndex = measure1SelectedIndex;
                cboRuleComparison.SelectedValue = comparison;

                if (multicomparison)
                {
                    rdoCompositeMeasure2.Checked = true;
                    string[] parts = comparedTo.Split(',');
                    if ((parts[1] == "+") || (parts[1] == "-"))
                    {
                        txtSumDiffMeasure2.Text = comparedTo.Replace(",", "");
                        rdoSumDiffMeasure2.Checked = true;
                    }
                }
                else
                {
                    if (comparedTo.StartsWith("["))
                    {
                        string value = comparedTo.Substring(1, comparedTo.Length - 2);
                        txtSpecificValueMeasure2.Text = value;
                        rdoSpecificValueMeasure2.Checked = true;
                    }
                    else
                    {
                        int measure2SelectedIndex = Int32.Parse(row["ComparedToOrderPos"].ToString());
                        for (int i = 0; i < cboAnotherDataMeasure2.Items.Count; i++)
                        {
                            ListItem x = (ListItem)cboAnotherDataMeasure2.Items[i];
                            int p = Int32.Parse(x.Value.ToString());
                            if (p == measure2SelectedIndex)
                            {
                                cboAnotherDataMeasure2.SelectedIndex = i;
                                break;
                            }
                        }
                        rdoAnotherDataMeasure2.Checked = true;
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnResetRule_Click(object sender, EventArgs e)
        {
            if (this.updating)
            {
                listViewReportRules_SelectedIndexChanged(null, null);
            }
            else
            {
                btnAddNewRule.Enabled = true;
                listViewReportRules.Enabled = true;
                btnResetRule.Text = "Reset";
                btnDeleteRule.Enabled = true;
                this.updating = true;
                gboReportRule.Text = "Updating Rule Details";
            }
        }

        private void btnDeleteRule_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            try
            {
                if (listViewReportRules.SelectedItems.Count > 0)
                {
                    ListViewItem item = listViewReportRules.SelectedItems[0];
                    string name = item.SubItems[1].Text;
                    DialogResult response = MessageBox.Show(this,
                        String.Format("Are you sure you want to delete {0}?", name),
                        AppConfiguration.ApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (response == System.Windows.Forms.DialogResult.Yes)
                    {
                        DataRow row = (DataRow)item.Tag;
                        int reportID = Int32.Parse(row["RepID"].ToString());
                        int ruleID = Int32.Parse(row["BRNo"].ToString());

                        Cursor.Current = Cursors.WaitCursor;
                        toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                        bool deleted = Utilities.DeleteReportRule(reportID, ruleID);
                        Cursor.Current = Cursors.Default;
                        toolStripStatusLabel.Text = "Ready";
                        
                        if (deleted)
                        {
                            MessageBox.Show(this,
                                String.Format("You have successfully deleted {0}", name),
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Utilities.ClearCache(DataCache.REPORTS_BUSINESS_RULES);
                            LoadReportRulesIntoListView();
                        }
                        else
                        {
                            MessageBox.Show(this,
                                String.Format("The process of deleting {0} did not complete", name),
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else return;
                }
                else
                {
                    MessageBox.Show(this, "Please select a report business rule to delete",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnSaveRule_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            #region Validation
            if (updating)
            {
                if (listViewReportRules.SelectedItems.Count < 1)
                {
                    MessageBox.Show(this, "Please select business rule to update!", AppConfiguration.ApplicationName,
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            if (String.IsNullOrEmpty(txtRuleDescription.Text))
            {
                MessageBox.Show(this, "Please provide rule description!", AppConfiguration.ApplicationName, 
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtRuleDescription.Focus();
                return;
            }

            if (cboRuleComparison.SelectedValue == null)
            {
                MessageBox.Show(this, "Please select type of comparison!", AppConfiguration.ApplicationName,
                   MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cboRuleComparison.Focus();
                return;
            }

            if (rdoSpecificValueMeasure2.Checked && rdoSpecificValueMeasure2.Enabled)
            {
                if (String.IsNullOrEmpty(txtSpecificValueMeasure2.Text))
                {
                    MessageBox.Show(this, "Please valid integer.",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtSpecificValueMeasure2.Focus();
                    return;
                }
            }

            if (rdoSumDiffMeasure2.Checked && rdoSumDiffMeasure2.Enabled)
            {
                if (String.IsNullOrEmpty(txtSumDiffMeasure2.Text))
                {
                    MessageBox.Show(this, "Please write data position separated by '+'.",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtSumDiffMeasure2.Focus();
                    return;
                }
                else
                {
                    string pattern = @"^\d{1,2}((-|\+)\d{1,2})+$";
                    Regex regex = new Regex(pattern);
                    if (!regex.IsMatch(txtSumDiffMeasure2.Text))
                    {
                        MessageBox.Show(this,
                            "Invalid Format. Please write data position separated by '+' or '-' sign",
                            AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtSumDiffMeasure2.Focus();
                        return;
                    }
                }
            }

            if (rdoExpressionMeasure2.Checked && rdoExpressionMeasure2.Enabled)
            {
                MessageBox.Show(this, "Comparison that involve more that two in average is not impleted",
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            if (rdoAverageMeasure2.Checked && rdoExpressionMeasure2.Enabled)
            {
                MessageBox.Show(this, "Comparison that involve more that two in average is not impleted",
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            #endregion

            #region Determining Business Rule Parameters
            ListItem item = (ListItem)cboReportsForRules.SelectedItem;
            int reportID = Int32.Parse(item.Value.ToString());

            item = (ListItem)cboRuleMeasure1.SelectedItem;
            int measurePosNo = Int32.Parse(item.Value.ToString());
            int comparisonType = Int32.Parse(cboRuleComparison.SelectedValue.ToString());
            string ruleDescription = txtRuleDescription.Text;
            bool multicomparison = false;
            string comparedToOrderPos = String.Empty;

            if (rdoCompositeMeasure2.Checked && rdoCompositeMeasure2.Enabled)
            {
                multicomparison = true;
                if (rdoSumDiffMeasure2.Checked && rdoSumDiffMeasure2.Enabled)
                {
                    string text = txtSumDiffMeasure2.Text;
                    text = text.Replace("+", "|");
                    text = text.Replace("-", "|");
                    string[] parts = text.Split('|');
                    
                    string[] operators = new string[parts.Length];
                    int index = 1;
                    string pattern = @"(-|\+)";
                    MatchCollection matches = Regex.Matches(txtSumDiffMeasure2.Text, pattern);
                    foreach (Match m in matches)
                    {
                        foreach (Group g in m.Groups)
                        {
                            string op = g.Value;
                            if (!String.IsNullOrEmpty(op))
                            {
                                operators[index] = op;
                                index++;
                                break;
                            }
                        }
                    }

                    //string[] parts = txtSumDiffMeasure2.Text.Split('+');
                    StringBuilder sBuilder = new StringBuilder();
                    sBuilder.Append(parts[0]);
                    for (int i = 1; i <parts.Length; i++)
                    {
                        sBuilder.Append(",");
                        sBuilder.Append(operators[i]);
                        sBuilder.Append(",");
                        sBuilder.Append(parts[i]);
                    }
                    comparedToOrderPos = sBuilder.ToString();
                }

                if (rdoExpressionMeasure2.Checked && rdoExpressionMeasure2.Enabled)
                {
                    MessageBox.Show(this, "Comparison that involves expression is not impleted",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }

                if (rdoAverageMeasure2.Checked && rdoAverageMeasure2.Enabled)
                {
                    MessageBox.Show(this, "Comparison that involves more that two in average is not impleted",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
            }
            else
            {
                multicomparison = false;
                if (rdoSpecificValueMeasure2.Checked && rdoSpecificValueMeasure2.Enabled)
                {
                    comparedToOrderPos = String.Format("[{0}]", txtSpecificValueMeasure2.Text);
                }

                if (rdoAnotherDataMeasure2.Checked && rdoAnotherDataMeasure2.Checked)
                {
                    item = (ListItem)cboAnotherDataMeasure2.SelectedItem;
                    comparedToOrderPos = item.Value.ToString();
                }
            }
            #endregion

            if (updating)
            {
                #region Updating
                DataRow row = (DataRow)listViewReportRules.SelectedItems[0].Tag;
                int BRNo = Int32.Parse(row["BRNo"].ToString());

                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                bool updated = Utilities.UpdateReportRule(reportID, measurePosNo, ruleDescription, 
                    comparedToOrderPos, comparisonType, multicomparison, BRNo);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";
                
                if (updated)
                {
                    MessageBox.Show(this, "You have successfully updated report business rule",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Utilities.ClearCache(DataCache.REPORTS_BUSINESS_RULES);
                    LoadReportRulesIntoListView();
                }
                else
                {
                    MessageBox.Show(this, "Updating of report business rule did not complete",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
            else
            {
                #region Inserting
                Cursor.Current = Cursors.WaitCursor;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                bool inserted = Utilities.InsertReportRule(reportID, measurePosNo, ruleDescription, 
                    comparedToOrderPos, comparisonType, multicomparison);
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";
                
                if (inserted)
                {
                    MessageBox.Show(this, "You have successfully inserted new report business rule",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    Utilities.ClearCache(DataCache.REPORTS_BUSINESS_RULES);
                    LoadReportRulesIntoListView();
                    btnResetRule_Click(null, null);
                }
                else
                {
                    MessageBox.Show(this, "Creation of new report business rule did not complete",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                #endregion
            }
        }

        private void rdoSpecificValueMeasure2_CheckedChanged(object sender, EventArgs e)
        {
            txtSpecificValueMeasure2.Enabled = rdoSpecificValueMeasure2.Checked;
        }

        private void rdoAnotherDataMeasure2_CheckedChanged(object sender, EventArgs e)
        {
            cboAnotherDataMeasure2.Enabled = rdoAnotherDataMeasure2.Checked;
        }

        private void rdoCompositeMeasure2_CheckedChanged(object sender, EventArgs e)
        {
            gboCompositeMeasure2.Enabled = rdoCompositeMeasure2.Checked;
        }

        private void rdoSumDifferenceMeasure2_CheckedChanged(object sender, EventArgs e)
        {
            txtSumDiffMeasure2.Enabled = rdoSumDiffMeasure2.Checked;
        }

        private void rdoAverageMeasure2_CheckedChanged(object sender, EventArgs e)
        {
            txtAverageMeasure2.Enabled = rdoAverageMeasure2.Checked;
        }

        private void btnAddNewRule_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            this.updating = false;
            btnAddNewRule.Enabled = false;
            listViewReportRules.Enabled = false;
            btnDeleteRule.Enabled = false;
            btnResetRule.Text = "Cancel";

            txtRuleDescription.Clear();
            txtSpecificValueMeasure2.Clear();
            txtSumDiffMeasure2.Clear();
            txtExpresionMeasure2.Clear();
            txtAverageMeasure2.Clear();
            gboReportRule.Text = "Adding New Rule Details";

            ListItem item = (ListItem) cboReportsForRules.SelectedItem;
            int reportID = Int32.Parse(item.Value.ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataLocations = Utilities.GetReportDataLocations(reportID);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboRuleMeasure1.Items.Clear();
            cboAnotherDataMeasure2.Items.Clear();
            foreach (DataRow r in dataLocations.Rows)
            {
                ListItem i = new ListItem();
                i.Text = r["DataDescription"].ToString();
                i.Value = r["DataPosition"];

                cboRuleMeasure1.Items.Add(i);
                cboAnotherDataMeasure2.Items.Add(i);
            }
            try
            {
                cboRuleMeasure1.SelectedIndex = 0;
                cboRuleMeasure1.DropDownWidth = DropDownWidth(cboRuleMeasure1);
            }
            catch { }
            try
            {
                cboAnotherDataMeasure2.SelectedIndex = 0;
                cboAnotherDataMeasure2.DropDownWidth = DropDownWidth(cboAnotherDataMeasure2);
            }
            catch { }
        }
        #endregion

        #region Private Helper Methods
        private void LoadReportNameListForRules()
        {
            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetAllExpectedReports();
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            
            cboReportsForRules.Items.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                ListItem item = new ListItem();
                item.Text = row["ReportName"].ToString();
                item.Value = row["RepID"];
                cboReportsForRules.Items.Add(item);
            }
            try
            {
                cboReportsForRules.SelectedIndex = 0;
            }
            catch { }
        }

        private void LoadReportRulesIntoListView()
        {
            ListItem item = (ListItem) cboReportsForRules.SelectedItem;
            int reportID = Int32.Parse(item.Value.ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetReportRules(reportID);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";
            
            listViewReportRules.Items.Clear();
            foreach (DataRow row in dataTable.Rows)
            {
                string position = row["MeasurePosNo"].ToString();
                string description = row["RuleDescription"].ToString();
                string[] columns = new string[] { position, description };
                ListViewItem i = new ListViewItem(columns, -1);
                i.Tag = row;
                listViewReportRules.Items.Add(i);
            }
            lblAvailableRules.Text = listViewReportRules.Items.Count.ToString();
            //if (listViewReportRules.Items.Count < 1) btnAddNewRule_Click(null, null);
            //else btnResetRule_Click(null, null);
        }

        private void LoadReportRuleDetails()
        {
            ListItem a = (ListItem)cboReportsForRules.SelectedItem;
            int reportID = Int32.Parse(a.Value.ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataLocations = Utilities.GetReportDataLocations(reportID);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            cboRuleMeasure1.Items.Clear();
            cboAnotherDataMeasure2.Items.Clear();
            foreach (DataRow r in dataLocations.Rows)
            {
                ListItem i = new ListItem();
                i.Text = r["DataDescription"].ToString();
                i.Value = r["DataPosition"];
                cboRuleMeasure1.Items.Add(i);
                cboAnotherDataMeasure2.Items.Add(i);
            }
            cboRuleMeasure1.DropDownWidth = DropDownWidth(cboRuleMeasure1);
            cboAnotherDataMeasure2.DropDownWidth = DropDownWidth(cboAnotherDataMeasure2);
            LoadReportRulesIntoListView();

            if (listViewReportRules.SelectedItems.Count < 1)
            {
                cboRuleMeasure1.SelectedIndex = 0;
                cboRuleComparison.SelectedValue = 0;
            }            
        }

        private static int DropDownWidth(ComboBox myCombo)
        {
            int maxWidth = myCombo.Width;
            int temp = 0;
            foreach (var obj in myCombo.Items)
            {
                string text = obj.ToString();
                temp = TextRenderer.MeasureText(text, myCombo.Font).Width;
                if (temp > maxWidth) maxWidth = temp;
            }
            return maxWidth;
        }
        #endregion
        #endregion

        #region Report Merge
        private void rdoMergeFacility_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMergeFacility.Checked)
            {
                try
                {
                    lblMergeLevel.Text = "Facility Name:";
                    DataTable dataTable = null;
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.FACILITY:
                            string facilityCode = this.authenticatedUser.AccessLevelValue;
                            dataTable = Utilities.GetFacilityDetails(facilityCode);
                            break;

                        case AccessLevel.DISTRICT:
                            int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetFacilitiesDetailsByDistrict(districtID);
                            break;

                        case AccessLevel.REGION:
                            int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetFacilitiesDetailsByRegion(regionID);
                            break;

                        default:
                            //dataTable = Utilities.GetAllFacilities();
                            dataTable = Utilities.GetAllFacilitiesStatus();
                            break;
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cboMergeLevel.DataSource = null;
                    cboMergeLevel.ValueMember = dataTable.Columns[0].ColumnName;
                    cboMergeLevel.DisplayMember = dataTable.Columns[1].ColumnName;
                    cboMergeLevel.DataSource = dataTable;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void rdoMergeDistrict_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMergeDistrict.Checked)
            {
                try
                {
                    lblMergeLevel.Text = "District Name:";
                    DataTable dataTable = null;
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.DISTRICT:
                            int districtID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetDistrict(districtID);
                            break;

                        case AccessLevel.REGION:
                            int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetDistrictsByRegion(regionID);
                            break;

                        default:
                            dataTable = Utilities.GetAllDistricts();
                            break;
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cboMergeLevel.DataSource = null;
                    cboMergeLevel.ValueMember = "DistrictNo";
                    cboMergeLevel.DisplayMember = "District";
                    cboMergeLevel.DataSource = dataTable;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void rdoMergeRegion_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMergeRegion.Checked)
            {
                try
                {
                    lblMergeLevel.Text = "Region Name:";
                    DataTable dataTable = null;
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.REGION:
                            int regionID = Int32.Parse(this.authenticatedUser.AccessLevelValue);
                            dataTable = Utilities.GetRegion(regionID);
                            break;

                        default:
                            dataTable = Utilities.GetAllRegions();
                            break;
                    }
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";

                    cboMergeLevel.DataSource = null;
                    cboMergeLevel.ValueMember = "RegionID";
                    cboMergeLevel.DisplayMember = "RegionName";
                    cboMergeLevel.DataSource = dataTable;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void rdoMergeNation_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMergeNation.Checked)
            {
                lblMergeLevel.Enabled = false;
                cboMergeLevel.Enabled = false;
            }
            else
            {
                lblMergeLevel.Enabled = true;
                cboMergeLevel.Enabled = true;
            }
        }

        private void tabPageReportManagementReportMerge_Enter(object sender, EventArgs e)
        {
            if (!tabPageReportManagementReportMergeLoaded)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable reportMerge = Merging.GetAllReportMerge();
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    lstReportMerge.Items.Clear();
                    foreach (DataRow row in reportMerge.Rows)
                    {
                        string name = row["Name"].ToString();
                        ListItem item = new ListItem();
                        item.Text = name;
                        item.Value = row;
                        lstReportMerge.Items.Add(item);
                    }

                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    DataTable dataTable = Utilities.GetAllReportYears();
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    foreach (DataRow row in dataTable.Rows)
                    {
                        string year = row["Year"].ToString();
                        cboMergeStartYear.Items.Add(year);
                        cboMergeEndYear.Items.Add(year);
                    }

                    Cursor.Current = Cursors.WaitCursor;
                    toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                    dataTable = Utilities.GetAllReportPeriods();
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    foreach (DataRow row in dataTable.Rows)
                    {
                        string period = row["Period"].ToString();
                        cboMergeStartPeriod.Items.Add(period);
                        cboMergeEndPeriod.Items.Add(period);
                    }
                    try
                    {
                        cboMergeStartYear.SelectedIndex = 0;
                        cboMergeEndYear.SelectedIndex = 0;
                        cboMergeStartPeriod.SelectedIndex = 0;
                        cboMergeEndPeriod.SelectedIndex = 0;
                    }
                    catch { }

                    switch (this.authenticatedUser.Level)
                    {
                        case AccessLevel.FACILITY:
                            rdoMergeDistrict.Enabled = false;
                            rdoMergeRegion.Enabled = false;
                            rdoMergeNation.Enabled = false;
                            break;

                        case AccessLevel.DISTRICT:
                            rdoMergeRegion.Enabled = false;
                            rdoMergeNation.Enabled = false;
                            break;

                        case AccessLevel.REGION:
                            rdoMergeNation.Enabled = false;
                            break;
                    }
                    tabPageReportManagementReportMergeLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private int lstReportMergeCurrentSelectedIndex = -1;    //My own management of selected index
        private void lstReportMerge_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstReportMerge.SelectedIndex == lstReportMergeCurrentSelectedIndex) return;
            else lstReportMergeCurrentSelectedIndex = lstReportMerge.SelectedIndex;
            
            try
            {
                if (lstReportMerge.SelectedIndex != -1)
                {
                    btnMergeReports.Enabled = true;
                    ListItem item = (ListItem)lstReportMerge.SelectedItem;
                    DataRow row = (DataRow)item.Value;
                    int mergeId = Int32.Parse(row["MergeId"].ToString());
                    string name = row["Name"].ToString();
                    string description = row["Description"].ToString();
                    
                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = string.Format("Loading {0}. Please wait", name);
                    Application.DoEvents();

                    var reportMergeView = eHostReportMergingView.Child as ReportMergingView;
                    reportMergeView.Reload(mergeId);

                    Cursor.Current = Cursors.Default;
                    toolStripStatusLabel.Text = "Ready";
                    return;

                    DataTable dataTable = Merging.GetDestinationMergingReport(mergeId);
                    //cboDestinationReport.Items.Clear();
                    //foreach (DataRow r in dataTable.Rows)
                    //{
                    //    ListItem i = new ListItem();
                    //    string reportName = r["ReportName"].ToString();
                    //    i.Text = reportName;
                    //    i.Value = r;
                    //    cboDestinationReport.Items.Add(i);
                    //}
                    //if (cboDestinationReport.Items.Count > 0) cboDestinationReport.SelectedIndex = 0;

                    //dgvSourceReports.Rows.Clear();

                    //TODO: Fix this in the auto-generated source file from designer of the main page
                    //DataTable sourceReportMerge = Merging.GetSourceMergingReport(mergeId);
                    //dgvSourceReports.DataSource = sourceReportMerge;

                    //cboSourceReport.Items.Clear();
                    //cboSourceReport.DisplayMember = "ReportName";
                    //cboSourceReport.ValueMember = "RepID";
                    //cboSourceReport.DataSource = sourceReportMerge;

                    //foreach (DataRow r in sourceReportMerge.Rows)
                    //{
                    //    ListItem i = new ListItem();
                    //    string reportName = r["ReportName"].ToString();
                    //    i.Text = reportName;
                    //    i.Value = r;
                    //    cboSourceReport.Items.Add(i);
                    //}
                    //cboSourceReport.ValueType = Type.GetType("System.Int32");

                    //foreach (DataRow r in sourceReportMerge.Rows)
                    //{
                    //    int sourceReportId = Int32.Parse(r["RepID"].ToString());

                    //    int rowIndex = dgvSourceReports.Rows.Add();
                    //    DataGridViewRow reportRow = dgvSourceReports.Rows[rowIndex];
                    //    DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)reportRow.Cells[0];

                    //    //int currentIndex = 0;
                    //    //foreach (ListItem i in cell.Items)
                    //    //{
                    //    //    int reportId = Int32.Parse(r["RepID"].ToString());
                    //    //    if (reportId == sourceReportId)
                    //    //    {
                    //    //        cell
                    //    //    }
                    //    //}
                    //    //cell.
                    //}
                    DataTable reportMergeIndicators = Merging.GetReportDataMerging(mergeId);
                    //DataTable reportIndicators = new DataTable();
                    //DataColumn column = new DataColumn("DestinationIndicator", Type.GetType("System.String"));
                    //reportIndicators.Columns.Add(column);
                    //column = new DataColumn("SourceIndicator", Type.GetType("System.String"));
                    //reportIndicators.Columns.Add(column);
                    //column = new DataColumn("Comment", Type.GetType("System.String"));
                    //reportIndicators.Columns.Add(column);



                    //foreach (DataRow r in reportMergeIndicators.Rows)
                    //{
                    //    int destinationReport = Int32.Parse(r["DestinationIndicator"].ToString());
                    //    DataTable report = Utilities.GetReportDetails(destinationReport);
                    //    foreach (DataRow d in report.Rows)
                    //    {
                    //        string repVersion = d["RepVersion"].ToString();
                    //    }

                    //    int sourceReport = Int32.Parse(r["SourceIndicator"].ToString());
                    //}
                    //dgvReportIndicators.DataSource = reportMergeIndicators;
                }
                else
                {
                    btnMergeReports.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void btnMergeReports_Click(object sender, EventArgs e)
        {
            btnMergeReports.Enabled = false;
            Application.DoEvents();
            try
            {
                bool overwrite = chbOverwriteReports.Checked;

                #region Validating user selection before processing the request
                if (!(rdoMergeFacility.Checked || rdoMergeDistrict.Checked || rdoMergeRegion.Checked || rdoMergeNation.Checked))
                {
                    MessageBox.Show(this, "Please select merging level",
                        AppConfiguration.ApplicationName,
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                ListItem item = (ListItem)lstReportMerge.SelectedItem;
                DataRow row = (DataRow)item.Value;
                int mergeId = Int32.Parse(row["MergeId"].ToString());
                DataTable sourceMergingReport = Merging.GetSourceMergingReports(mergeId);
                List<int> sourceReports = new List<int>();
                foreach (DataRow r in sourceMergingReport.Rows)
                {
                    string sRepId = r["RepID"].ToString();
                    int iRepId = Int32.Parse(sRepId);
                    sourceReports.Add(iRepId);
                }

                int startYear = Int32.Parse(cboMergeStartYear.Text);
                int startMonth = Int32.Parse(cboMergeStartPeriod.Text);
                int endYear = Int32.Parse(cboMergeEndYear.Text);
                int endMonth = Int32.Parse(cboMergeEndPeriod.Text);
                if (endYear < startYear)
                {
                    MessageBox.Show(this, "Please select valid time frame",
                        AppConfiguration.ApplicationName,
                        MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    if ((endYear == startYear) && (endMonth < startMonth))
                    {
                        MessageBox.Show(this, "Please select valid time frame",
                            AppConfiguration.ApplicationName,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                #endregion

                string senderNum = String.Format("{0} [{1} Level - Data Merging]",
                                this.authenticatedUser.FullName, this.authenticatedUser.AccessLevelText);

                #region Retrieving required facilities
                toolStripStatusLabel.Text = "Merging reports. Please wait...";
                Application.DoEvents();
                DataTable requiredFacilities = null;
                MergingOperationStatus status = null;
                if (rdoMergeFacility.Checked)
                {
                    string code = cboMergeLevel.SelectedValue.ToString();
                    status = Merging.MergeFacilityReports(mergeId, overwrite, code, startYear, startMonth, endYear, endMonth, senderNum);
                }
                if (rdoMergeDistrict.Checked)
                {
                    string sValue = cboMergeLevel.SelectedValue.ToString();
                    int districtId = Int32.Parse(sValue);
                    status = Merging.MergeDistrictReports(mergeId, overwrite, districtId, startYear, startMonth, endYear, endMonth, senderNum);
                }

                if (rdoMergeRegion.Checked)
                {
                    string sValue = cboMergeLevel.SelectedValue.ToString();
                    int regionId = Int32.Parse(sValue);
                    status = Merging.MergeRegionReports(mergeId, overwrite, regionId, startYear, startMonth, endYear, endMonth, senderNum);
                }

                if (rdoMergeNation.Checked)
                {
                    requiredFacilities = Utilities.GetAllFacilitiesStatus();
                    status = Merging.MergeNationReports(mergeId, overwrite, startYear, startMonth, endYear, endMonth, senderNum);
                }
                #endregion

                toolStripStatusLabel.Text = "Ready";
                MessageBox.Show(this,
                    String.Format("The operation completed successfully. {0}{0}" +
                        "Reports submitted: {1}{0}" +
                        "Reports accepted: {2}{0}" +
                        "Reports already existed: {3}{0}" +
                        "Reports rejected: {4}{0}" +
                        "Reports overwritten: {5}{0}" +
                        "{0}For more details check the logs.",
                        Environment.NewLine, status.TotalSubmitted, status.TotalReportAccepted, status.TotalAlreadyExisting,
                        status.TotalRejected, status.TotalReportOverwritten),
                    AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
            finally
            {
                btnMergeReports.Enabled = true;
            }
        }
        #endregion
    }
}
